﻿exports.map = function (req, res) {
    var pconfig = require("../common/config").config;
    var Commons = require("../common/Commons").Commons;
    var DBUtils = null;
    var deviceId = req.query.devid?req.query.devid:null;
    var startDate = req.query.start?req.query.start:null;
    var endDate = req.query.end?req.query.end:null;
    var rTime = null;
    if (startDate) {
        rTime = { $gte: startDate};
    }
    if (endDate) {
        if (rTime) {
            rTime.$lte = endDate;
        } else {
            rTime = { $lte: endDate };
        }
    }
    var dbType = pconfig.useDB;
    var url;
    if (dbType == "mongo") {
        url = pconfig.dbUrl;
        DBUtils = require("../common/MongoDBUtils").DBUtils;
    } else if (dbType == "mysql") {
        url = pconfig.mysqlConfig;
        DBUtils = require("../common/MysqlDBUtils").DBUtils;
    }
    var p = DBUtils.getConnection(url, null);
    p.then(function (rdb) {
        var db = rdb.result;
        var qp=DBUtils.find(db, "gps", { "deviceId": deviceId, recordTime: rTime });
        qp.then(function (r) {
            var data = r.result;
            if (data && data.length > 0) {
                res.render('map', { result: data, first: data[0] });
            } else {
                res.render('map', { result: [], first: null });
            }
            Commons.finishDBAndSetResult(db, dbType, res, false, true);         
        }).catch(function (err) {
            console.log(err);
            Commons.finishDBAndSetResult(db, dbType, res, false, true);
            res.render('map', { result: [], first: null });
        });
    }).catch(function (err) {
        console.log(err);
        Commons.finishDBAndSetResult(db, dbType, res, false, true);
    });
    
};